package com.kb.design.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.design.dto.CheckValueDTO;
import com.kb.design.entity.CheckValue;
import com.kb.design.entity.CustomUser;
import com.kb.design.entity.DesignProject;
import com.kb.design.enums.DesignStatus;
import com.kb.design.mapper.postgreSQL.CheckValueMapper;
import com.kb.design.mapper.postgreSQL.CustomUserMapper;
import com.kb.design.mapper.postgreSQL.ProjectMapper;
import com.kb.design.service.CheckValueService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 检查结果表;(check_value)表服务接口实现类
 * @author : czx
 * @date : 2025-9-4
 */
@Service
@DS("slave-1")
public class CheckValueServiceImpl extends ServiceImpl<CheckValueMapper, CheckValue> implements CheckValueService {
    @Resource
    private CheckValueMapper checkValueMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private CustomUserMapper userMapper;
    /**
     * 通过ID查询单条数据
     *
     * @return 实例对象
     */
    public CheckValueDTO queryOne(CheckValueDTO checkValue) {
        LambdaQueryWrapper<CheckValue> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CheckValue::getProjectId, checkValue.getProjectId())
                .eq(CheckValue::getCheckedBy, checkValue.getCheckedBy())
                .eq(CheckValue::getDel, 0)
                .last("limit 1");
        CheckValue poRow = checkValueMapper.selectOne(queryWrapper);
        //查询上一次检查结果
        LambdaQueryWrapper<CheckValue> query = Wrappers.lambdaQuery();
        query.eq(CheckValue::getProjectId, checkValue.getProjectId())
                .eq(CheckValue::getCheckedBy, checkValue.getCheckedBy())
                .eq(CheckValue::getDel, 1)
                .eq(CheckValue::getVersion, poRow.getVersion()-1)
                .last("limit 1");
        CheckValue data = checkValueMapper.selectOne(query);
        if (data != null){
            poRow.setReview(data.getReview());
        }
        CheckValueDTO dtoRow = BeanUtil.copyProperties(poRow,CheckValueDTO.class);
        BeanUtil.copyProperties(poRow,dtoRow,true);
        dtoRow.setCheckResults(null);
        return dtoRow;
    }

    /**
     * 分页查询
     *
     * @param checkValue 筛选条件
     * @return 分页查询结果
     */
    public Map<String, Object> paginQuery(CheckValueDTO checkValue) {
        Map<String, Object> page =new HashMap<>();
        List<CheckValueDTO> valueDTOS = checkValueMapper.queryByPage(checkValue);
        page.put("pageList", valueDTOS);
        // 提取各个阶段的最新数据
        List<CheckValueDTO> latestData = valueDTOS.stream()
                .collect(Collectors.groupingBy(CheckValueDTO::getNodeName)) // 按nodeName分组
                .values().stream()
                .map(list -> list.stream()
                        .max(Comparator.comparing(CheckValueDTO::getCreateTime)) // 获取每组中createTime最新的数据
                        .orElse(null))
                .filter(Objects::nonNull) // 过滤掉null值
                .toList();
        //翻译字段
        for (CheckValueDTO latestDatum : latestData) {
            latestDatum.setNodeName(translateNodeName(latestDatum.getNodeName()));
            latestDatum.setCheckResultsName(translateCheckResults(latestDatum.getCheckResults()));
        }
        page.put("results", latestData);
        return page;
    }
    /**
     * 翻译节点名称
     * @param checkResults
     * @return
     */
    private String translateCheckResults(Integer checkResults) {
        switch (checkResults) {
            case 1:
                return "进行中";
            case 2:
                return "通过";
            case 3:
                return "不通过";
            default:
                return checkResults.toString();
        }
    }
    /**
     * 翻译结果
     * @param nodeName 节点代码
     * @return 翻译后的节点名称
     */
    private String translateNodeName(String nodeName) {
        switch (nodeName) {
            case "1":
                return "封装负责人";
            case "2":
                return "封装主管";
            case "5":
                return "设计主管";
            case "6":
                return "valor负责人";
            default:
                return nodeName; // 如果没有匹配的翻译，返回原始值
        }
    }
    /**
     * 新增数据
     *
     * @param checkValue 实例对象
     * @return 实例对象
     */
    public CheckValueDTO insert(CheckValueDTO checkValue){
        CheckValue poRow = BeanUtil.copyProperties(checkValue,CheckValue.class);
        checkValueMapper.insert(poRow);
        return BeanUtil.copyProperties(checkValue,CheckValueDTO.class);
    }

    /**
     * 更新数据
     *
     * @param checkValue 实例对象
     * @return 实例对象
     */
    @DSTransactional
    public boolean update(CheckValueDTO checkValue){
        CheckValue poRow = BeanUtil.copyProperties(checkValue, CheckValue.class);
        checkValueMapper.updateById(poRow);
        //去除权限字段
        DesignProject designProject = projectMapper.selectById(checkValue.getProjectId());
        List<Integer> checkPersonList = designProject.getCheckPersonList();
        //获取valor 部门的人
        List<Integer> list;
        if (Objects.equals(checkValue.getCheckType(),3)){
            List<Integer> longs = userMapper.queryByFunction("3");
            list = designProject.getCheckPersonList().stream()
                    .filter(item -> !longs.contains(item))
                    .toList();
        }else {
            list = checkPersonList.stream().filter(item -> !Objects.equals(item, Integer.valueOf(checkValue.getCheckedBy()))).toList();
        }
        designProject.setCheckPersonList(list);


        //判断是否全部检查完 : 列表里面的检查结果都为 1
        List<CheckValue> valueList = checkValueMapper.selectList(Wrappers.lambdaQuery(CheckValue.class).eq(CheckValue::getProjectId, checkValue.getProjectId())
                .eq(CheckValue::getDel, 0));
        boolean allCheckResultsAreOne = valueList.stream()
                .allMatch(item -> Objects.equals(item.getCheckResults(), 2));
        if (allCheckResultsAreOne){
            designProject.setStatus(DesignStatus.CASTING_BOARD.getIndex());
            designProject.setCheckPersonList(new ArrayList<>());
            //消息通知
            List<CustomUser> userList = userMapper.queryUserByDeptFunctions("10");
            String codes = userList.stream()
                    .map(CustomUser::getCode)
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(","));
            if (CollUtil.isNotEmpty(userList)){
                com.kb.util.MessageUtil.sentMessage(codes, "叮！项目：" + designProject.getProjectName() + "，项目编号：" + designProject.getProjectNumber() + "，已完成QA检查，请及时进行奖金分配。", "任务提醒");
            }
        }
        projectMapper.updateById(designProject);
        return true;
    }

    @Override
    public boolean processing(CheckValueDTO checkValue) {
        //旧数据更新为1
        CheckValue entity = BeanUtil.copyProperties(checkValue, CheckValue.class);
        entity.setDel(1);
        checkValueMapper.updateById(entity);
        //生成一条新的数据
        CheckValue poRow = BeanUtil.copyProperties(checkValue, CheckValue.class);
        poRow.setId( null);
        poRow.setCheckResults(1);
        poRow.setDel(0);
        poRow.setVersion(checkValue.getVersion()+1);
        poRow.setCreateBy(checkValue.getCreateBy());
        //项目待检查字段塞回检查人字段
        DesignProject designProject = projectMapper.selectById(checkValue.getProjectId());
        List<Integer> checkPersonList = designProject.getCheckPersonList();
        checkPersonList.add(Integer.valueOf(poRow.getCheckedBy()));
        designProject.setCheckPersonList(checkPersonList);
        projectMapper.updateById(designProject);
        return checkValueMapper.insert(poRow)>0;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public Integer deleteById(long id){
        return checkValueMapper.deleteById(id);
    }
}
